package com.lmscn.lms.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.BuildPaperUtil;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.JsonKit;

import java.util.*;

/**
 * Created by quxingyu on 2015/8/6.
 */
public class CourseExamController extends Controller {
    /**
     * 课程考试说明
     */
    public void examInfo() {

        Long courseId = getParaToLong("courseId");
        Long studentId = getParaToLong("studentId");
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Exam courseExam = Exam.dao.getCourseExam(courseId, "courseexam");
        Long examedTimes = 0l;
        if (courseExam != null) {
            // 已完成考试次数
            examedTimes = TestpaperResult.dao.getTestpaperCount(studentId, courseExam.getLong("id"), "courseexam", 1, -1);
        }
        CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
        double totalScore = 0;
        if (courseStudent != null) {
            totalScore = courseStudent.getDouble("score");
        }
        QuestionCategory questionCategory = QuestionCategory.dao.getQuestionCategory(courseId, "course");
        if (questionCategory != null) {// 判断是否有题库
            dataMap.put("msg", "1");
        } else {
            dataMap.put("msg", "0");
        }
        String testInfo = CommonUtil.testInfo;
        StringBuilder stringBuilder = new StringBuilder("1.每位考生");
        if (courseExam.getInt("times") == 0) {
            stringBuilder.append("不限考试次数，");
        } else {
            stringBuilder.append("有" + courseExam.getInt("times") + "次考试机会，");
        }
        stringBuilder.append("考试时间" + courseExam.getInt("limited_time") + "分钟。\n 2.试卷满分" + courseExam.getInt("score") + "分，及格分" +
                "" + courseExam.getInt("pass_proportion") + "分。\n 3.试卷共有试题" + courseExam.getInt("item_count") + "道。");
        String examInfo = stringBuilder.toString();
        dataMap.put("testInfo", testInfo);
        dataMap.put("examInfo", examInfo);
        dataMap.put("totalScore", totalScore);
        dataMap.put("examedTimes", examedTimes);
        dataMap.put("times", courseExam.getInt("times"));
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }


    /**
     * 查看课程考试成绩0929
     */
    public void examScore() {
        Long courseId = getParaToLong("courseId");
        Long studentId = getParaToLong("studentId");
        Exam courseExam = Exam.dao.getCourseExam(courseId, "courseexam");
        TestpaperResult testpaperResult = TestpaperResult.dao.findMaxScore(studentId, courseExam.getLong("id"), "courseexam");
        Map<String, Object> dataMap = new HashMap<String,Object>();
        dataMap.put("score", testpaperResult.getInt("score"));
        dataMap.put("usedTime", testpaperResult.getInt("used_time"));
        dataMap.put("testpaperId",testpaperResult.getLong("testpaper_id"));
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 手机端点击进入考试，生成试卷，并返回试卷详情
     */
    @Before(Tx.class)
    public void buildExam() {
        Long id = getParaToLong("courseId");
        Long studentId = getParaToLong("studentId");
        Map<String, Object> finalMap = new HashMap<String, Object>();//最终容器
        Map<String, Object> dataMapList = new HashMap<String, Object>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        int answeredNum = 0;
        TestpaperResult testpaperResult = null;
        List<TestpaperResult> list = new ArrayList<TestpaperResult>();
        //通过课程ID查看是否存在课程考试
        Exam exam = Exam.dao.getCourseExam(id, "courseexam");

        if (exam == null) {//如果不存在课程考试
            //查看是否存在课程相关设置
            CourseLearningSetting courseLearningSetting = CourseLearningSetting.dao.findByCourseId(id);
            //根据课程设置，创建考试
            Exam new_exam = getModel(Exam.class);
            new_exam.saveExam(courseLearningSetting, new_exam);
            dataMapList = BuildPaperUtil.BuildExamPaper(new_exam, studentId);
            list = TestpaperResult.dao.getTestpaperResult(studentId, new_exam.getLong("id"), "courseexam", 0, -1, null);
            if (list.size() > 0) {
                testpaperResult = list.get(0);
            }
        } else {//如果存在课程考试
            if (BuildPaperUtil.isTwiceExam(studentId, exam.getLong("id"), "courseexam")) {// 判断考试几次
                //查看该学员是否存在未完成的试卷
                list = TestpaperResult.dao.getTestpaperResult(studentId, exam.getLong("id"), "courseexam", 0, -1, null);
                if (list.size() > 0) { //如果大于0，说明存在未完成的答卷
                    testpaperResult = (TestpaperResult) list.get(0);
                    //获取试卷都有哪些题目
                    List questionList = TestpaperItem.dao.getQuestionList(testpaperResult.getLong("testpaper_id"));
                    //获取学员已经答了哪些题。
                    List studentQuestionList = TestpaperItemResult.dao.getQuestionList(testpaperResult.getLong("testpaper_id"), studentId);
                    //把选项赋给题目
                    List questions = new ArrayList();
                    for (int i = 0; i < questionList.size(); i++) {
                        Question question = (Question) questionList.get(i);
                        List questionMetasList = QuestionMetas.dao.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
                        for (int j = 0; j < questionMetasList.size(); j++) {
                            QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                            question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                        }
                        questions.add(question);
                    }
                    Map<String, Object> questionsMap = new HashMap<String, Object>();
                    questionsMap.put("question", questions);
                    questionsMap.put("answered", studentQuestionList);
                    if (questionsMap.size() == 0 || studentQuestionList.size() == 0) {
                        questionsMap.put("msg", "无考题");
                    }
                    dataMapList.put("questions", questionsMap);
                    dataMap.put("answeredNum", studentQuestionList.size());
                    answeredNum = studentQuestionList.size();
                } else { //学员不存在未完成的答卷，则直接生成试卷
                    dataMapList = BuildPaperUtil.BuildExamPaper(exam, studentId);
                    list = TestpaperResult.dao.getTestpaperResult(studentId, exam.getLong("id"), "courseexam", 0, -1, null);
                    if (list.size() > 0) {
                        testpaperResult = list.get(0);
                    }
                }
                if (answeredNum == 0) {
                    dataMap.put("answeredNum", 0);
                }
            } else {
                dataMap.put("error_code", 1);
                dataMap.put("msg", "考试已超过限制次数");
                finalMap.put("testPaper", dataMap);
                renderJson(JsonKit.mapToJson(finalMap, 39));
            }
        }
        dataMap.put("limited_time", testpaperResult.getInt("limited_time"));
        dataMap.put("used_time", testpaperResult.getInt("used_time"));
        dataMap.put("testpaper_id", testpaperResult.getLong("testpaper_id"));
        dataMap.put("questionAbout", dataMapList);
        finalMap.put("testPaper", dataMap);
        renderJson(JsonKit.mapToJson(finalMap, 39));
    }

    /**
     * 手机端点击进入测试，生成试卷，并返回试卷详情
     */
    @Before(Tx.class)
    public void buildTest() {
        Long id = getParaToLong("courseId");
        Long studentId = getParaToLong("studentId");
        Map<String, Object> finalMap = new HashMap<String, Object>();//最终容器
        Map<String, Object> dataMapList = new HashMap<String, Object>();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        int answeredNum = 0;
        TestpaperResult testpaperResult = null;
        List<TestpaperResult> list = new ArrayList<TestpaperResult>();
        //通过课程ID查看是否存在课程考试
        Test test = Test.dao.getTest(id, "coursetest");

        if (test == null) {//如果不存在课程考试
            //查看是否存在课程相关设置
            CourseLearningSetting courseLearningSetting = CourseLearningSetting.dao.findByCourseId(id);
            //根据课程设置，创建考试。
            Test new_test = getModel(Test.class);
            new_test.saveTest(courseLearningSetting, new_test);
            dataMapList = BuildPaperUtil.BuildTestPaper(new_test, studentId);
            list = TestpaperResult.dao.getTestpaperResult(studentId, new_test.getLong("id"), "coursetest", 0, -1, null);
            if (list.size() > 0) {
                testpaperResult = list.get(0);
            }
        } else {//如果存在课程考试
            //查看该学员是否存在未完成的试卷
            list = TestpaperResult.dao.getTestpaperResult(studentId, test.getLong("id"), "coursetest", 0, -1, null);
            if (list.size() > 0) {//如果大于0，说明存在未完成的答卷

                testpaperResult = list.get(0);
                //获取试卷都有哪些题目
                List questionList = TestpaperItem.dao.getQuestionList(testpaperResult.getLong("testpaper_id"));
                //获取学员已经答了哪些题。
                List studentQuestionList = TestpaperItemResult.dao.getQuestionList(testpaperResult.getLong("testpaper_id"), studentId);
                //把选项赋给题目
                List questions = new ArrayList();
                for (int i = 0; i < questionList.size(); i++) {
                    Question question = (Question) questionList.get(i);
                    List questionMetasList = QuestionMetas.dao.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
                    for (int j = 0; j < questionMetasList.size(); j++) {
                        QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                        question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                    }
                    questions.add(question);
                }
                Map<String, Object> questionsMap = new HashMap<String, Object>();
                questionsMap.put("question", questions);
                questionsMap.put("answered", studentQuestionList);
                dataMapList.put("questions", questionsMap);
                dataMap.put("answeredNum", studentQuestionList.size());
                answeredNum = studentQuestionList.size();
            } else {//学员不存在未完成的答卷，则直接生成试卷
                dataMapList = BuildPaperUtil.BuildTestPaper(test, studentId);
                list = TestpaperResult.dao.getTestpaperResult(studentId, test.getLong("id"), "coursetest", 0, -1, null);
                if (list.size() > 0) {
                    testpaperResult = list.get(0);
                }
            }
        }
        if (answeredNum == 0) {
            dataMap.put("answeredNum", 0);
        }
        dataMap.put("limited_time", testpaperResult.getInt("limited_time"));
        dataMap.put("testpaper_id", testpaperResult.getLong("testpaper_id"));
        dataMap.put("questionAbout", dataMapList);
        finalMap.put("testPaper", dataMap);
        renderJson(JsonKit.mapToJson(finalMap, 39));
    }

}
